#include "MyScene.h"
#include "qforeach.h"

using namespace Esri::ArcGISRuntime;

MyScene::MyScene(QWidget* parent /*=nullptr*/):
    QMainWindow(parent)
{
    CPLSetConfigOption("GTIFF_SRS_SOURCE","EPSG");
    GDALAllRegister();

    //将默认底图设置为OsmStandard(中文地图)
    m_scene = new Scene(BasemapStyle::OsmStandard, this);
    ArcGISTiledElevationSource* elevationSource =
        new ArcGISTiledElevationSource(
            QUrl("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"),
            this);


    m_scene->baseSurface()->elevationSources()->append(elevationSource);
    m_sceneView = new SceneGraphicsView(m_scene, this);

    m_viewPointLay = new GraphicsOverlay(this);
    m_sceneView->graphicsOverlays()->append(m_viewPointLay);

    m_picIcnLay = new GraphicsOverlay(this);
    m_sceneView->graphicsOverlays()->append(m_picIcnLay);

    m_picIcnLayByClick = new GraphicsOverlay(this);
    m_sceneView->graphicsOverlays()->append(m_picIcnLayByClick);


    m_picFrameLay = new GraphicsOverlay(this);
    m_sceneView->graphicsOverlays()->append(m_picFrameLay);


    m_shapeFileLay = new GraphicsOverlay(this);
    m_sceneView->graphicsOverlays()->append(m_shapeFileLay);

    fClickPhoto = new Graphic;

    flb1 = new FLabel(this);
    //FLabel的image指针
    fimg = new QImage;

    flb2 = new FLabel(this);

    jd = new QLineEdit;
    jd->setFixedSize(50,20);

    wd = new QLineEdit;
    wd->setFixedSize(50,20);

    initCam();

    QLabel *btName = new QLabel(this);
    btName->setText("显示影像");
    btName->setAlignment(Qt::AlignCenter);
    btName->setStyleSheet("QLabel{background:white;color:blue;border-radius:10px}");

    fb1 = new SwitchBt(50,20);
    fb1->setObjectName("rasSwitch");
    fb1->setFixedWidth(50);
    connect(fb1,&QToolButton::clicked,this,&MyScene::showRaster);



    //    setStyleSheet("#fileBtn{background:rgb(180,180,180);color:white;border-radius:10px}"
    //                  "#viewBtn{background:rgb(231,12,32);color:white;border-radius:15px}");
    QHBoxLayout *ct1 = new QHBoxLayout;
    ct1->addWidget(btName);
    ct1->addWidget(fb1);


    //ct5为显示OSM窗口
    //    QLabel *btName1 = new QLabel(this);
    //    btName1->setText("显示OSM");
    //    btName1->setAlignment(Qt::AlignCenter);
    //    btName1->setStyleSheet("QLabel{background:white;color:blue;border-radius:10px}");

    //    fb2 = new SwitchBt(50,20);
    //    fb2->setObjectName("OSMSwtich");
    //    fb2->setFixedWidth(50);
    //    connect(fb2,&QToolButton::clicked,this,&MyScene::showOSM);
    //    QHBoxLayout *ct5 = new QHBoxLayout;
    //    ct5->addWidget(btName1);
    //    ct5->addWidget(fb2);

    QPushButton *mbtn1 = new QPushButton;
    mbtn1->setText("添加SHAPE");
    mbtn1->setObjectName("fileBtn");
    mbtn1->setFixedHeight(30);
    connect(mbtn1,&QPushButton::clicked,this,&MyScene::createShapeFeature);

    QPushButton *mbtn6 = new QPushButton;
    mbtn6->setVisible(false);
    mbtn6->setText("-");
    mbtn6->setObjectName("clearShapeBtn");
    mbtn6->setFixedHeight(30);
    connect(mbtn6,&QPushButton::clicked,this,&MyScene::hideShapeBtn);

    QHBoxLayout *ct6 = new QHBoxLayout;
    ct6->addWidget(mbtn1);
    ct6->addWidget(mbtn6);

    QVBoxLayout *ct2 = new QVBoxLayout;
    ct2->addLayout(ct6);

    QPushButton *mbtn2 = new QPushButton;
    mbtn2->setText("选择照片文件夹");
    mbtn2->setObjectName("fileBtn");
    mbtn2->setFixedHeight(30);
    connect(mbtn2,&QPushButton::clicked,this,&MyScene::addPicDir);

    QPushButton *mbtn5= new QPushButton;
    mbtn5->setText("清除标记点");
    mbtn5->setFixedHeight(30);
    connect(mbtn5,&QPushButton::clicked,this,&MyScene::clearWidget);

    QPushButton *mbtn4= new QPushButton;
    mbtn4->setText("TEST1");
    mbtn4->setFixedHeight(30);
    mbtn4->setObjectName("fileBtn");
    connect(mbtn4,&QPushButton::clicked,this,&MyScene::functionTest);

    ct2->addWidget(mbtn2);
    ct2->addWidget(mbtn5);
    ct2->addWidget(mbtn4);

    QVBoxLayout *ct3 = new QVBoxLayout;
    ct3->addLayout(ct1);
    //ct5为显示OSM窗口
    //    ct3->addLayout(ct5);
    ct3->addLayout(ct2);

    QWidget *btsWt = new QWidget(m_sceneView);
    btsWt->setLayout(ct3);
    btsWt->setGeometry(10,50,130,200);

    QPushButton *mbtn3= new QPushButton;
    mbtn3->setText("View");
    mbtn3->setObjectName("viewBtn");
    mbtn3->setFixedHeight(30);
    connect(mbtn3,&QPushButton::clicked,this,&MyScene::initCam);

    QPushButton *mbtn7= new QPushButton;
    mbtn7->setText("CP");
    mbtn7->setObjectName("clearViewPoint");
    mbtn7->setFixedHeight(30);
    connect(mbtn7,&QPushButton::clicked,this,&MyScene::clearViewPoint);

    QHBoxLayout *ct4 = new QHBoxLayout;
    ct4->addWidget(mbtn3);
    ct4->addWidget(jd);
    ct4->addWidget(wd);
    ct4->addWidget(mbtn7);
    QWidget *viewBts = new QWidget(m_sceneView);
    viewBts->setLayout(ct4);
    viewBts->setGeometry(10,10,200,50);

    QWidget *sw2 = new QWidget(this);
    swct1 =new QVBoxLayout(sw2);
    swct1->setObjectName("swct1");
    sw2->setObjectName("scArBack");
    sw2->setStyleSheet("#scArBack{background:rgba(16,174,35,53)}");

    picScrollArea =new QScrollArea(this);
    picScrollArea->setWidget(sw2);
    picScrollArea->setWidgetResizable(true);
    picScrollArea->setGeometry(10,240,150,300);
    picScrollArea->setVisible(false);

    QFile file(":/style.qss");
    file.open(QFile::ReadOnly);
    QString styleSheet = tr(file.readAll());

    setStyleSheet(styleSheet);

    setCentralWidget(m_sceneView);
}

void MyScene::mousePressEvent(QMouseEvent *event)
{
    switch (event->button())
    {
    case Qt::LeftButton:
    {
        double x = event->position().toPoint().x();
        double y = event->position().toPoint().y();

        QPointF myP(x,y);

        Point myP2 = m_sceneView->screenToBaseSurface(x,y);
        jd->setText(QString::number(myP2.x(),'f',4));
        wd->setText(QString::number(myP2.y(),'f',4));

        tp1 = new Graphic;
        QFuture<Esri::ArcGISRuntime::IdentifyGraphicsOverlayResult *> re = m_sceneView->identifyGraphicsOverlayAsync(m_picFrameLay,myP,5,false,1);

        if(re.result()->graphics().length()>0)
        {
            tp1 = re.result()->graphics()[0];
            QString picPath = tp1->attributes()->attributeValue("picPath").toString();
            tp1->deleteLater();
            flb1->setVisible(true);
            flb1->setGeometry(x,y,400,400);
            creatFLabelPhoto(picPath);
            flb1->aniGrp->stop();
            flb1->aniGrp->start();


        }
        else
        {
            flb1->setVisible(false);
        }


        //        显示shape信息
        QFuture<Esri::ArcGISRuntime::IdentifyGraphicsOverlayResult *> re2 = m_sceneView->identifyGraphicsOverlayAsync(m_shapeFileLay,myP,5,false,1);
        if(re2.result()->graphics().length()>0)
        {
            tp1 = re2.result()->graphics()[0];
            tp1->setSelected(true);
            QString sName = tp1->attributes()->attributeValue("Name").toString();

            flb2->setVisible(true);
            QPixmap *backPic = new QPixmap(":/1.jpg");
            flb2->setGeometry(x,y,200,50);
            flb2->setInfo(sName);
            flb2->setPic(backPic);
            flb2->aniGrp->stop();
            flb2->aniGrp->start();
        }
        else
        {
            m_shapeFileLay->clearSelection();
            flb2->setVisible(false);
        }
    }
    break;
    default:
        break;
    }

}


void MyScene::wheelEvent(QWheelEvent *event)
{

    if(!m_viewPointLay->graphics()->isEmpty())
    {
        double myValue = m_sceneView->currentViewpointCamera().location().z();
        fPointSymbol->setWidth(myValue/50);
        fPointSymbol->setDepth(myValue/50);
        fPointSymbol->setHeight(myValue/50);
    }
}


// destructor
MyScene::~MyScene()
{
}

void MyScene::createShapeFeature()
{
    QString shpFile = QFileDialog::getOpenFileName(this,"选择shp","","Shape(*.shp)");
    if(shpFile.isNull())
    {
        return;
    }

    std::string shpFile2= shpFile.toStdString();
    const char *shpFile3 =shpFile2.c_str();
    GDALDataset *m_shapeFile = (GDALDataset*)GDALOpenEx(shpFile3,GDAL_OF_VECTOR,NULL,NULL, NULL);
    OGRLayer *ly = m_shapeFile->GetLayer(0);

    //point
    simpleMarkerSymbol =
        new SimpleMarkerSymbol(
            SimpleMarkerSymbolStyle::Triangle,
            QColor("blue"),
            14.0f /*size*/,
            this);
    const SpatialReference spatialRef(4326);
    //polyline
    simpleLineSymbol =
        new SimpleLineSymbol(
            SimpleLineSymbolStyle::Solid,
            QColor("blue"),
            0.5f /*width*/,
            this);
    //polygon
    polygonSymbol = new SimpleFillSymbol(
        SimpleFillSymbolStyle::Solid, // Fill style
        QColor(255, 131, 0,100), // Fill color, RGB orange
        new SimpleLineSymbol( // Outline
            SimpleLineSymbolStyle::Solid, // Outline style
            QColor(35,24,185,100), // Outline color
            2.0, // Outline width (float)
            this
            ),
        this
        );

    int fType = ly->GetGeomType();

    if (fType==1){
        int feCount = ly->GetFeatureCount();
        for(int i=0;i<feCount;i++){
            OGRFeature *fe = ly->GetFeature(i);
            OGRGeometry *ge = fe->GetGeometryRef();
            double temp_x = ge->toPoint()->getX();
            double temp_y = ge->toPoint()->getY();
            Point *myPoint = new Point(temp_x,temp_y,spatialRef);
            QVariantMap m_Pm_attr;
            m_Pm_attr["Name"]=  fe->GetFieldAsString(0);

            m_shapeFileLay->graphics()->append(new Graphic(*myPoint,m_Pm_attr,simpleMarkerSymbol,this));
        }
    }else if(fType==2){
        int feCount = ly->GetFeatureCount();
        for(int i=0;i<feCount;i++)
        {
            polylineBuilder = new PolylineBuilder(SpatialReference::wgs84());
            OGRFeature *fe = ly->GetFeature(i);

            QVariantMap m_Pm_attr;
            m_Pm_attr["Name"]=  fe->GetFieldAsString(0);


            //获取全字段
//            for(int k=0;k<5;k++){
//                qDebug()<<fe->GetFieldAsString(k);
//            }



            OGRGeometry *ge = fe->GetGeometryRef();

            for(int j=0;j<ge->toLineString()->getNumPoints();j++){
                double temp_x = ge->toLineString()->getX(j);
                double temp_y = ge->toLineString()->getY(j);
                polylineBuilder->addPoint(temp_x,temp_y);
            }
            Polyline m_pl = polylineBuilder->toPolyline();
            m_shapeFileLay->graphics()->append(new Graphic(m_pl,m_Pm_attr,simpleLineSymbol,this));
        }
    }else if(fType==3){

        int feCount = ly->GetFeatureCount();
        for(int i=0;i<feCount;i++)
        {
            polygonBuilder = new PolygonBuilder(SpatialReference::wgs84());
            OGRFeature *fe = ly->GetFeature(i);

            QVariantMap m_Pm_attr;
            m_Pm_attr["Name"]=  fe->GetFieldAsString(1);

            OGRGeometry *ge = fe->GetGeometryRef();
            OGRPolygon *polygon = ge->toPolygon();
            polygon->getExteriorRing()->get_Area();
            for(int i=0;i<polygon->getExteriorRing()->getNumPoints();i++)
            {
                double x_temp = polygon->getExteriorRing()->getX(i);
                double y_temp = polygon->getExteriorRing()->getY(i);
                polygonBuilder->addPoint(x_temp,y_temp);
            }
            Polygon m_pm = polygonBuilder->toPolygon();
            Graphic* polygonGraphic = new Graphic(m_pm,m_Pm_attr, polygonSymbol, this);
            m_shapeFileLay->graphics()->append(polygonGraphic);
        }

    }

//    OGRFeatureDefn *poDefn = ly->GetLayerDefn();
//    int fieldCount = poDefn->GetFieldCount();
//    for(int i=0;i<fieldCount;i++)
//    {
//        OGRFieldDefn* poFieldDefn = poDefn->GetFieldDefn(i);
//        fieldInfo.append(poFieldDefn->GetNameRef());
//    }


//    //    int geType = ly->GetGeomType();
//    int feCount = ly->GetFeatureCount();
//    for(int i=0;i<feCount;i++)
//    {
//        polygonBuilder = new PolygonBuilder(SpatialReference::wgs84());
//        OGRFeature *fe = ly->GetFeature(i);

//        QVariantMap m_Pm_attr;
//        m_Pm_attr["Name"]=  fe->GetFieldAsString(0);

//        //        for(int j=0;j<fieldInfo.length();j++)
//        //        {
//        //            qDebug()<<fieldInfo[j] + ":" + fe->GetFieldAsString(j);
//        //        }

//        OGRGeometry *ge = fe->GetGeometryRef();
//        OGRPolygon *polygon = ge->toPolygon();
//        polygon->getExteriorRing()->get_Area();
//        for(int i=0;i<polygon->getExteriorRing()->getNumPoints();i++)
//        {
//            double x_temp = polygon->getExteriorRing()->getX(i);
//            double y_temp = polygon->getExteriorRing()->getY(i);
//            polygonBuilder->addPoint(x_temp,y_temp);
//        }
//        Polygon m_pm = polygonBuilder->toPolygon();
//        Graphic* polygonGraphic = new Graphic(m_pm,m_Pm_attr, polygonSymbol, this);
//        m_shapeFileLay->graphics()->append(polygonGraphic);
//    }
    QPushButton *fbtn1 = this->findChild<QPushButton*>("clearShapeBtn");
    fbtn1->setVisible(true);
};

void MyScene::addPicDir()
{

    clearWidget();

    QString path=QFileDialog::getExistingDirectory();
    if(path.isEmpty())
    {
        return;
    }
    QStringList picList;
    QDirIterator it(path,
                    QStringList()<<"*.jpg",
                    QDir::Files ,
                    QDirIterator::Subdirectories);
    while(it.hasNext())
    {
        it.next();
        if(checkPicInfo(it.filePath()))
        {
            picList.append(it.filePath());
        }
    };
    for(int i=0;i<picList.length();i++)
    {
        //创建一个点位圆球
        //        creatPicPoint(picList[i]);
        //创建一个照片的图标
        creatPhotoFrame(picList[i]);
    }

    std::function<QMap<QString,QImage>(const QString&)> loadImgs = [](const QString &picPath)
    {
        QImage image(picPath);
        QImage img_scaled = image.scaled(QSize(100, 100), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        QMap<QString,QImage> map;
        map.insert(picPath,img_scaled);
        return map;
    };

    QFuture<QMap<QString,QImage>> picMapList = QtConcurrent::mapped(picList,loadImgs);
    picMapList.waitForFinished();

    foreach (QMap map, picMapList) {
        addPicToScrollArea(map.firstKey(),map.first());
    }

    picScrollArea->setVisible(true);

    initCam();
}

void MyScene::functionTest()
{
    Raster* raster = new Raster("E:\\FPictures\\rasters\\措普84.tif", this);
    RasterLayer* rasterLayer = new RasterLayer(raster, this);

    m_scene->basemap()->baseLayers()->append(rasterLayer);

    //        double x = m_sceneView->currentViewpointCamera().location().x();
    //        double y = m_sceneView->currentViewpointCamera().location().y();
    //        double z = m_sceneView->currentViewpointCamera().location().z();
    //        double heading = m_sceneView->currentViewpointCamera().heading();
    //        double pitch = m_sceneView->currentViewpointCamera().pitch();
    //        double roll = m_sceneView->currentViewpointCamera().roll();
    //        qDebug()<<x<<y<<z<<heading<<pitch<<roll;

    //    const Point tp(102.10995278,29.67097500,SpatialReference::wgs84());
    //    QFuture<double> re = m_scene->baseSurface()->elevationAsync(tp);
    //    re.then([](double elev){
    //        qDebug()<<elev;
    //    });
    //    clearWidget();

//    QString picPath = "E:\\FPictures\\2024_04_13_09_23_IMG_3335.JPG";
//    std::string pic2 = picPath.toStdString();
//    const char * pszFile = pic2.c_str();
//    GDALDataset *picDataset = (GDALDataset*)GDALOpen(pszFile, GA_ReadOnly);

//    QString xCnText = picDataset->GetMetadataItem("EXIF_GPSLatitude","");
//    int xDu = xCnText.split(')')[0].replace('(',"").toInt();
//    int xFen = xCnText.split(')')[1].replace('(',"").toInt();
//    double xMiao;
//    QString xMiao_Str = xCnText.split(')')[2].replace('(',"").replace(' ',"");
//    if(xMiao_Str.contains(".")){
//        xMiao= xMiao_Str.split('.')[0].toDouble() + xMiao_Str.split('.')[1].toDouble()/100;
//    }else{
//        xMiao = xMiao_Str.toDouble();
//    }

//    qDebug()<<xMiao;

//    double picGPSX = xDu + xFen/60.0 + xMiao/3600.0;

//    qDebug()<<picGPSX;


//    double xMiao_a = xCnText.split(')')[2].replace('(',"").split('.')[0].toDouble();
//    double xMiao_b = xCnText.split(')')[2].replace('(',"").split('.')[1].toDouble();

//    double xMiao = xMiao_a + xMiao_b/100;

//    double picGPSX = xDu + xFen/60.0 + xMiao/3600.0;



}

void MyScene::initCam()
{
    double x = 99.324;
    double y = 26.2261;
    double z = 259400.0;
    double heading = 14.0;
    double pitch = 60.0;
    double roll = 0.0;
    sceneCamera = new Camera(y, x, z, heading, pitch, roll);
    //    m_sceneView->setViewpointCameraAndWait(sceneCamera);
    m_sceneView->setViewpointCamera(*sceneCamera);

    double inputX = jd->text().toDouble();
    double inputY = wd->text().toDouble();
    if(inputX==0 && inputY==0){
        m_sceneView->setViewpointCamera(*sceneCamera);
    }else{
        sceneCamera = new Camera(inputY, inputX, 10000, heading, 0, roll);
        creatViewPoint(inputX,inputY);
        m_sceneView->setViewpointCamera(*sceneCamera);
    }
}

void MyScene::showRaster()
{
    if(this->findChild<SwitchBt *>("rasSwitch")->isChecked())
    {
        Basemap* basemap = new Basemap(BasemapStyle::ArcGISImagery);
        m_scene->setBasemap(basemap);
    }
    else
    {
        Basemap* basemap = new Basemap(BasemapStyle::OsmStandard);
        m_scene->setBasemap(basemap);
    }
}

void MyScene::showOSM()
{
    if(this->findChild<SwitchBt *>("OSMSwtich")->isChecked())
    {
        Basemap* basemap = new Basemap(BasemapStyle::OsmStandard);
        m_scene->setBasemap(basemap);
    }
    else
    {
        Basemap* basemap = new Basemap(BasemapStyle::ArcGISTopographic);
        m_scene->setBasemap(basemap);
    }
}

void MyScene::creatViewPoint(double x,double y)
{
    m_viewPointLay->graphics()->clear();

    Point *fp1 = new Point(x,y,SpatialReference::wgs84());
    fPointSymbol = new SimpleMarkerSceneSymbol(
        SimpleMarkerSceneSymbolStyle::Sphere,
        QColor(11,163,134),
        50, 50, 50,
        SceneSymbolAnchorPosition::Center, this
        );

    Graphic* pointGraphic2 = new Graphic(*fp1,fPointSymbol, this);

    m_viewPointLay->graphics()->append(pointGraphic2);
}

void MyScene::creatPicPoint(QString picPath)
{
    double x = picGPS(picPath).at(0);
    double y = picGPS(picPath).at(1);

    Point *fp1 = new Point(x,y,SpatialReference::wgs84());
    SimpleMarkerSceneSymbol* fPointSymbol = new SimpleMarkerSceneSymbol(
        SimpleMarkerSceneSymbolStyle::Sphere,
        QColor(213,163,134),
        5, 5, 5,
        SceneSymbolAnchorPosition::Center, this
        );
    Graphic* pointGraphic2 = new Graphic(*fp1,fPointSymbol, this);
    m_picIcnLay->graphics()->append(pointGraphic2);
}

void MyScene::creatPicInfoIcon(double x,double y,QString picPath)
{
    m_picIcnLayByClick->graphics()->clear();
    QImage *imgIcon = new QImage(":/5578093.png");
    Point mtP(x,y,SpatialReference::wgs84());
    PictureMarkerSymbol* fSymbol1 = new PictureMarkerSymbol(*imgIcon);
    fSymbol1->setHeight(30);
    fSymbol1->setWidth(30);
    QVariantMap picAttr;
    picAttr["picPath"] = picPath;

    Graphic* pointGraphic2 = new Graphic(mtP,picAttr,fSymbol1, this);
    pointGraphic2->setZIndex(1);
    m_picIcnLayByClick->graphics()->append(pointGraphic2);
    m_picIcnLayByClick->setSceneProperties(LayerSceneProperties(SurfacePlacement::RelativeToScene));

}

bool MyScene::checkPicInfo(QString picPath)
{
    std::string pic2 = picPath.toStdString();
    const char * pszFile = pic2.c_str();
    GDALDataset *picDataset = (GDALDataset*)GDALOpen(pszFile, GA_ReadOnly);
    QString xCnText = picDataset->GetMetadataItem("EXIF_GPSLongitude","");
    if(xCnText.isEmpty())
    {
        return false;
    }
    else
    {
        return true;
    }
}

void MyScene::creatPhotoFrame(QString picPath)
{
    //不使用照片本身的GPS-Z值
    double x = picGPS(picPath).at(0);
    double y = picGPS(picPath).at(1);
    //    double z = picGPS(picPath).at(2);

    QImage *imgIcon = new QImage(":/1671080.png");

    //    Point mtP(x,y,z,SpatialReference::wgs84());
    Point mtP(x,y,SpatialReference::wgs84());

    PictureMarkerSymbol* fSymbol1 = new PictureMarkerSymbol(*imgIcon);
    fSymbol1->setHeight(20);
    fSymbol1->setWidth(20);
    QVariantMap picAttr;
    picAttr["picPath"] = picPath;

    Graphic* pointGraphic2 = new Graphic(mtP,picAttr,fSymbol1, this);
    pointGraphic2->setZIndex(10);
    pointGraphic2->setObjectName("photoFrame");
    pointGraphic2->setProperty("picPath",picPath);
    pointGraphic2->setObjectName(picPath);

    m_picFrameLay->graphics()->append(pointGraphic2);
    m_picFrameLay->setSceneProperties(LayerSceneProperties(SurfacePlacement::RelativeToScene));


}

void MyScene::creatFLabelPhoto(QString picPath)
{


    int o = picGPS(picPath).at(3);
    fimg = new QImage(picPath);
    picRot = new QTransform;
    switch (o)
    {
    case 1:
        break;
    case 3:
        picRot->rotate(180);
        *fimg = fimg->transformed(*picRot,Qt::FastTransformation);
        break;
    case 6:
        picRot->rotate(90);
        *fimg = fimg->transformed(*picRot,Qt::FastTransformation);
        break;
    case 8:
        picRot->rotate(-90);
        *fimg = fimg->transformed(*picRot,Qt::FastTransformation);
        break;
    default:
        break;
    }
    QPixmap *np =new QPixmap(QPixmap::fromImage(*fimg));
    flb1->setPic(np);

    double x = picGPS(picPath).at(0);
    double y = picGPS(picPath).at(1);
    double z = picGPS(picPath).at(2);
    QString X_T = QString::number(x,'f',8);
    QString Y_T = QString::number(y,'f',8);
    QString Z_T = QString::number(z,'f',2);
    QString D_T = picDateTime(picPath);
    QString N_T = picPath.split("/").last();
    flb1->setInfo(D_T,N_T,X_T,Y_T,Z_T);


}

void MyScene::addPicToScrollArea(QString picPath,QImage img)
{
    int o = picGPS(picPath).at(3);
    double x = picGPS(picPath).at(0);
    double y = picGPS(picPath).at(1);
    QImage *fimg = &img;
    picRot = new QTransform;
    switch (o)
    {
    case 1:
        break;
    case 3:
        picRot->rotate(180);
        *fimg = fimg->transformed(*picRot,Qt::FastTransformation);
        break;
    case 6:
        picRot->rotate(90);
        *fimg = fimg->transformed(*picRot,Qt::FastTransformation);
        break;
    case 8:
        picRot->rotate(-90);
        *fimg = fimg->transformed(*picRot,Qt::FastTransformation);
        break;
    default:
        break;
    }
    QPixmap *np =new QPixmap(QPixmap::fromImage(*fimg));
    QLabel *l = new QLabel;
    l->setProperty("pic_x",x);
    l->setProperty("pic_y",y);
    l->setProperty("picPath",picPath);
    l->setScaledContents(true);
    //    l->setAlignment(Qt::AlignCenter);
    l->installEventFilter(this);
    l->setPixmap(*np);
    l->setFixedSize(80,80);
    swct1->addWidget(l);
}

bool MyScene::eventFilter(QObject *obj, QEvent *event)
{

    QLabel *t2 = qobject_cast<QLabel *>(obj);

    pw = t2->geometry().size().width();
    ph = t2->geometry().size().height();

    //    t2->setAlignment(Qt::AlignCenter);
    t2->setScaledContents(true);

    /*控制QLable实现动画*/
    if (event->type() == QEvent::Enter)
    {
        t2->setFixedSize(pw + 10,ph);
        return true;
    }
    else if(event->type() == QEvent::Leave)
    {
        t2->setFixedSize(pw - 10,ph);
        return true;
    }
    else if (event->type() == QEvent::MouseButtonPress)
    {


        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if(mouseEvent->button() == Qt::LeftButton)
        {
            flb1->setVisible(false);

            double x = t2->property("pic_x").toDouble();
            double y = t2->property("pic_y").toDouble();
            double z = m_sceneView->currentViewpointCamera().location().z();
            Camera *picCameraCn = new Camera(y,x,z,0,0,0);
            m_sceneView->setViewpointCamera(*picCameraCn);

            QString picPath = t2->property("picPath").toString();

            creatPicInfoIcon(x,y,picPath);

            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

void MyScene::hideShapeBtn(){
    m_shapeFileLay->graphics()->clear();
    QPushButton *fbtn1 = this->findChild<QPushButton*>("clearShapeBtn");
    fbtn1->setVisible(false);
}

QList<double> MyScene::picGPS(QString picPath)
{
    std::string pic2 = picPath.toStdString();
    const char * pszFile = pic2.c_str();
    GDALDataset *picDataset = (GDALDataset*)GDALOpen(pszFile, GA_ReadOnly);

    QString xCnText = picDataset->GetMetadataItem("EXIF_GPSLongitude","");
    int xDu = xCnText.split(')')[0].replace('(',"").toInt();
    int xFen = xCnText.split(')')[1].replace('(',"").toInt();

    double xMiao;
    QString xMiao_Str = xCnText.split(')')[2].replace('(',"").replace(' ',"");
    if(xMiao_Str.contains(".")){
        xMiao= xMiao_Str.split('.')[0].toDouble() + xMiao_Str.split('.')[1].toDouble()/100;
    }else{
        xMiao = xMiao_Str.toDouble();
    }
    double picGPSX = xDu + xFen/60.0 + xMiao/3600.0;


    QString yCnText = picDataset->GetMetadataItem("EXIF_GPSLatitude","");
    int yDu = yCnText.split(')')[0].replace('(',"").toInt();
    int yFen = yCnText.split(')')[1].replace('(',"").toInt();

    double yMiao;
    QString yMiao_Str = yCnText.split(')')[2].replace('(',"").replace(' ',"");
    if(yMiao_Str.contains(".")){
        yMiao= yMiao_Str.split('.')[0].toDouble() + yMiao_Str.split('.')[1].toDouble()/100;
    }else{
        yMiao = yMiao_Str.toDouble();
    }
    double picGPSY = yDu + yFen/60.0 + yMiao/3600.0;

    QString zCnText = picDataset->GetMetadataItem("EXIF_GPSAltitude","");
    double picGPSZ = zCnText.replace('"',"").replace('(',"").replace(')',"").toDouble();

    QString Orientation = picDataset->GetMetadataItem("EXIF_Orientation","");
    double picOrient = Orientation.toDouble();

    QList<double> picGPS;
    picGPS<<picGPSX<<picGPSY<<picGPSZ<<picOrient;

    return picGPS;
}

QString MyScene::picDateTime(QString picPath)
{
    std::string pic2 = picPath.toStdString();
    const char * pszFile = pic2.c_str();
    GDALDataset *picDataset = (GDALDataset*)GDALOpen(pszFile, GA_ReadOnly);

    QString dateTime = picDataset->GetMetadataItem("EXIF_DateTime","");

    return dateTime;
}

void MyScene::clearWidget(){
    QLayoutItem *item;
    while((item = swct1->takeAt(0)) != nullptr){
        item->widget()->removeEventFilter(this);
        swct1->removeWidget(item->widget());
        delete item->widget();
        picScrollArea->setVisible(false);
    }
    m_picIcnLayByClick->graphics()->clear();
    m_picIcnLay->graphics()->clear();
    m_picFrameLay->graphics()->clear();
}


void MyScene::clearViewPoint(){
    if(!m_viewPointLay->graphics()->isEmpty())
    {
        m_viewPointLay->graphics()->clear();
    }
}
































